<?php

/**
 * This class represents a collection of RadioButtons, it can only have RadioButton elements as its children.
 *
 * @author Matthijs Steen
 * @since 2008-08-02
 * @package Form.Containers
 */
class CheckboxContainer extends FormContainer {

	private $checked = null;

	/**
	 * Enter description here...
	 *
	 * @var RadioButton
	 */
	private $checkedChild = null;
	
	/**
	 * Sets up the CheckboxContainer
	 *
	 * @param String $name
	 * @param String $label
	 */
	function __construct( $name, $class = '', $label = '' ) {
		$this->name = $name;
		$this->setProperties(array('class' => $class, 'label' => $label));
	}

	/**
	 * Adds a child to this element, overridden method.
	 *
	 * @param Checkbox $button
	 */
	public function addChild( Checkbox $button ) {
		$button->setName( $this->name );
		if( $button->getValue() == $this->checked ) {
			$button->setChecked( $this->checked );
			$this->checkedChild = $button;
		}	

		parent::addChild( $button );
	}

	/**
	 * Sets the value of the element that should be selected.
	 *
	 * @param String $selected
	 */
	public function setChecked( $checked ) {
		if ( $checked instanceof Checkbox ) {
			$this->checked = $checked->getValue ( );
			$this->checkedChild = $checked;
		} else {
			if( $this->hasChildren() ) {
				foreach( $this->children as $child ) {
					if( $child->getValue() == $checked ) {
						$child->setChecked( true );
					}
				}
			}
		}
	}

	/**
	 * Returns the selected child element.
	 *
	 * @return RadioButton
	 */
	public function getChecked() {
		return $this->checkedChild;
	}

	/**
	 *
	 * @see FormNode::__toString()
	 */
	public  function __toString() {
		if( !$this->hasChildren() ) return ''; 
		$output = '<div class="'.( $this->getProperty("class") != '' ? $this->getProperty("class") : 'checkboxgroup' ).'"  id="' . $this->name . '">';
		if ($this->getProperty('label') != ''){
			$output .= '<label>'.$this->getProperty("label").'</label>';
		}
		
		foreach( $this->children as $button ) {
			$output .= $button;
		}

		$output .= '</div>';
		return $output;
	}
}


?>